import base64
import pickle

from django_redis import get_redis_connection
from redis import StrictRedis


def merge_cart_cookie_to_redis(request, response, user):
    """
    合并cookie中的购物车数据到redis中
    遇到cookie与redis中出现相同商品时以cookie数据为主，覆盖redis中的数据
    :param rquest: 请求对象，用于获取cookie
    :param response: 响应对象，用于清除cookie
    :param user: 登录用户，用于获取用户id
    :return:
    """
    # 获取cookie数据（base64字符串）
    cookie_cart = request.COOKIES.get('cart')
    if not cookie_cart:
        return response

    # 2.base64字符串-->字典
    # {2: {'count':1, 'selected':False}, 3: {'count':1, 'selected':False}}
    dict_cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
    # 3.合并cookie数据到redis中
    redis_conn = get_redis_connection('cart')   # type: StrictRedis
    pl = redis_conn.pipeline()
    for sku_id, dict_count_selected in dict_cookie_cart.items():
        count = dict_count_selected['count']
        selected = dict_count_selected['selected']
        pl.hset('cart_%s' % user.id, sku_id, count)
        if selected:
            pl.sadd('cart_selected_%s' % user.id, sku_id)
        else:
            pl.srem('cart_selected_%s' % user.id, sku_id)
        pl.execute()
        # 4. 清除cookie数据
        response.delete_cookie('cart')
        # 5. 返回响应
        return response